package com.alit.face.koala.service.upload;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Optional;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alit.face.koala.entity.UploadFileEntity;
import com.alit.face.koala.projectvariable.PVK;
import com.alit.face.koala.repository.UploadFileRepository;
import com.alit.face.koala.util.ImageUtil;
import com.litong.utils.projectvariable.PVU;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class UploadService {
  @Autowired
  private FileSaveSerivce fileSaveSerivce;
  @Autowired
  private UploadFileRepository uploadFileRepository;
  @Autowired
  private Environment environment;

  /**
   * 1.获取文件md5,查询数据库
   * 2.数据库中不存在,上传文件,保存到数据,返回
   *  
   */
  public UploadFileEntity upload(MultipartFile file) {
    byte[] bytes = null;
    try {
      bytes = file.getBytes();
    } catch (IOException e) {
      e.printStackTrace();
    }
    // 文件名
    String originalFileName = file.getOriginalFilename();
    // 拓展名
    String extension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
    UploadFileEntity upload = upload(bytes, extension);
    return upload;

  }

  public UploadFileEntity upload(byte[] bytes, String extension) {
    UploadFileEntity retval = null;
    String md5Hex = DigestUtils.md5Hex(bytes);
    // f124
    Optional<UploadFileEntity> optional = uploadFileRepository.findById(md5Hex);
    if (optional.isPresent()) {
      retval = optional.get();
      retval.setBytes(bytes);
      retval.setFullUri(getFullUri(retval.getUri()));
      retval.setLocalFilePath(getLocalFilePath(retval.getUri()));
      return retval;
    }
    // 文件输入流
    ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
    String uri = fileSaveSerivce.saveInputStream(inputStream, bytes.length, extension, null);
    log.info("上传文件成功:" + uri);
    retval = new UploadFileEntity();
    retval.setMd5(md5Hex);
    retval.setBytes(bytes);
    retval.setUri(uri);
    retval.setFullUri(getFullUri(retval.getUri()));
    retval.setLocalFilePath(getLocalFilePath(retval.getUri()));
    uploadFileRepository.save(retval);
    return retval;
  }

  private String getLocalFilePath(String uri) {
    String staticPath = PVU.getValue(PVK.projectStaticPath);
    return staticPath + File.separator + uri;
  }

  public String getFullUri(String uri) {
    String contextPath = environment.getProperty("server.servlet.context-path");
    return contextPath + uri;
  }

  /**
   * 上传人脸识别图片,如果图片大于2M,则缩放后上传 
   */
  public UploadFileEntity uploadImageFace(String base64) {
    byte[] decodeBase64 = Base64.decodeBase64(base64);
    return uploadImageFace(decodeBase64);
  }

  /**
   * 上传人脸识别图片,如果图片大于2M,则缩放后上传
   */
  private UploadFileEntity uploadImageFace(byte[] bytes) {
    String type = ImageUtil.getImageFormatByBytes(bytes);
    UploadFileEntity retval = uploadImageFace(bytes, type);
    return retval;
  }

  /**
   * 上传人脸识别图片,如果图片大于2M,则缩放后上传
   */
  public UploadFileEntity uploadImageFace(byte[] bytes, String extension) {
    while (bytes.length > 1500000) {
      bytes = ImageUtil.reduce(bytes);
      log.info("图片过大,缩放后的图片是:" + bytes.length);
    }
    UploadFileEntity retval = upload(bytes, extension);
    return retval;
  }

  public String getFullUriById(String md5Hex) {
    Optional<UploadFileEntity> entity = uploadFileRepository.findById(md5Hex);
    String uri = null;
    if (entity.isPresent()) {
      uri = entity.get().getUri();
      // log.info("从数据中查询到到图片:" + md5Hex+","+uri);
    }
    uri = getFullUri(uri);
    return uri;
  }
}
